package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.lang.System.in;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private  WorkspaceService workspaceService;
    /**
     * 获取营业额
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        //开始日期不等于结束日期
        while(!begin.equals(end)){
            //开始日期加一天
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //创建集合存放每日营业额
        List<Double> turnoverList = new ArrayList<>();
        //便利得到每一天的日期
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            //设置开始时间
            map.put("begin",beginTime);
            //设置结束时间
            map.put("end",endTime);
            //设置订单状态
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            //当日没有营业额turnover会为空，不为0，手动置0
            turnover=  turnover == null ? 0.0 : turnover;
            //添加当日营业额到集合
            turnoverList.add(turnover);
        }

        //封装数据返回
        return  TurnoverReportVO
                    .builder()
                    .dateList(StringUtils.join(dateList,","))
                    .turnoverList(StringUtils.join(turnoverList,","))
                    .build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUser(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        //开始日期不等于结束日期
        while(!begin.equals(end)){
            //开始日期加一天
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //创建集合存放每日营业额
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        //便利得到每一天的日期
        for (LocalDate date : dateList) {
            //设置时间信息
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //新建集合存放查询数据
            Map map = new HashMap();
            //设置开始时间
            map.put("begin",beginTime);
            //设置结束时间
            map.put("end",endTime);
            //统计当日新增用户
            Integer users = userMapper.sumByMap(map);
            //统计截至当日总用户数
            Integer totalUser = userMapper.countUser(map);
            //添加用户数据到集合
            newUserList.add(users);
            totalUserList.add(totalUser);
        }

        //封装数据返回
        return   UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    /**
     * 销量top10统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        //创建集合存放销量、商品名称
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();
        //新建集合存放查询数据
        Map map = new HashMap();
        //设置开始时间
        map.put("begin",begin);
        //设置结束时间
        map.put("end",end);
        //设置订单状态
        map.put("status", Orders.COMPLETED);
        //统计日期区间内销量前十数据
       List<GoodsSalesDTO>  goodsSalesList = orderDetailMapper.countSalesTop(map);
        //遍历返回数据
        for (GoodsSalesDTO sales : goodsSalesList) {
            nameList.add(sales.getName());
            numberList.add(sales.getNumber());
        }


        //封装数据返回
        return   SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrder(LocalDate begin, LocalDate end) {
        //创建集合存放日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        //计算日期列表
        while(!begin.equals(end)){
            //开始日期加一天
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //创建集合存放每日有效订单和总订单数
        //每日有效订单
        List<Integer> validOrderCountList = new ArrayList<>();
        //每日总单量
        List<Integer> orderCountList = new ArrayList<>();
        //遍历得到每一天的日期
        for (LocalDate date : dateList) {
            //设置具体时间信息
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //统计当日有效订单数
            Integer validOrder = getOrderReportVO(beginTime, endTime, Orders.COMPLETED);
            //统计当日总订单数
            Integer blanketOrder = getOrderReportVO(beginTime, endTime,null);
            //添加订单数据集合
            validOrderCountList.add(validOrder);
            orderCountList.add(blanketOrder);
        }
        //统计当日有效总订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //统计总订单数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //统计订单完成率
        Double orderCompletionRate= 0.0;
        if(validOrderCount !=0){
            orderCompletionRate   = validOrderCount.doubleValue() / totalOrderCount;
        }
        //封装数据返回
        return   OrderReportVO
                .builder()
                .totalOrderCount(totalOrderCount) //总订单数
                .validOrderCount(validOrderCount)   //日有效总订单数
                .orderCompletionRate(orderCompletionRate) //订单完成率
                .validOrderCountList(StringUtils.join(validOrderCountList,",")) //每日有效订单集合
                .orderCountList(StringUtils.join(orderCountList,","))   //每日总订单集合
                .dateList(StringUtils.join(dateList,",")) //日期集合
                .build();

    }

    /**
     * 导出运营数据报表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //获取30天前的日期
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        //获取到昨天的日期
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        //查询数据概览
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //通过POI将数据写入到Excel文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板创建一个新的excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //获取文件里面的sheet页
            XSSFSheet sheet = excel.getSheetAt(0);

            //填充数据 ---时间
            sheet.getRow(1).getCell(1).setCellValue("时间："+ dateBegin+" 至 " +dateEnd);

            //获取第四行
            XSSFRow row = sheet.getRow(3);
            //填充第四行第三列的营业额数据
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            //填充第四行第五列的订单完成率
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            //填充第四行第七列的新增用户数
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获取第五行
            row = sheet.getRow(4);
            //填充第五行第三列的有效订单
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            //填充第五行第五列的平均客单价
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());
            
            
            //填充明细数据
            //获取每天的各类数据

            for (int i = 0; i < 30; i++) {
                //计算每一天的日期
                LocalDate localDate = dateBegin.plusDays(i);
                //查询获取到每天的数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(localDate, LocalTime.MIN), LocalDateTime.of(localDate, LocalTime.MAX));
                //获取行
                row = sheet.getRow(7+i);
                //设置当前行第2列日期
                row.getCell(1).setCellValue(localDate.toString());
                //设置当前行第3列营业额
                row.getCell(2).setCellValue(businessData.getTurnover());
                //设置当前行第4列有效订单
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                //设置当前行第5列订单完成率
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                //设置当前行第6列平均客单价
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                //设置当前行第7列新增用户数
                row.getCell(6).setCellValue(businessData.getNewUsers());

            }


            //通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);


            //释放资源
            out.close();
            excel.close();

        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * 抽取方法调用mapper
     * @param begin
     * @param end
     * @param status
     * @return
     */
    private Integer getOrderReportVO(LocalDateTime begin, LocalDateTime end, Integer status ) {
        //新建集合存放查询数据
        Map map = new HashMap();
        //设置开始时间
        map.put("begin",begin);
        //设置结束时间
        map.put("end",end);
        //设置订单状态为已完成
        map.put("status", status);
        return  userMapper.countByMap(map);
    }
}
